<?php

namespace App\Models;

use App\Services\MyPimpableTrait;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Question extends Model
{
    use HasFactory, MyPimpableTrait;

    const TYPE = ['radio', 'checkbox', 'judge', 'fill', 'short', 'subsystem'];

    // 提供可搜索的字段
    public $searchable = ['category_id', 'type', 'title', 'status', 'created_at', 'updated_at', 'level', 'pid'];

    protected $vague = ['title'];

    // 可批量赋值的字段
    protected $fillable = [
        'user_id',
        'category_id',
        'type',
        'title',
        'content',
        'answer',
        'success_answer',
        'status',
        'fraction',
        'num',
        'success_num',
        'error_num',
        'level',
        'analysis',
        'order',
        'pid',
    ];

    // 属性转换
    protected $casts = [
        'created_at' => 'date:Y-m-d H:i:s',
        'updated_at' => 'date:Y-m-d H:i:s',
    ];

    // 设置默认排序字段
    protected $defaultSortCriteria = ['id,desc'];

    // 排序关键字
    protected $sortParameterName = 'sortBy';

    /**
     * 和用户的关联
     *
     * @return BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    /**
     * 子母题的关联
     *
     * @return HasMany
     */
    public function subsystem()
    {
        return $this->hasMany(Question::class, 'pid', 'id');
    }


    /**
     * 和分类的关联
     *
     * @return BelongsTo
     */
    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id', 'id');
    }

    /**
     * 设置答案选项访问器
     *
     * @param $value
     * @return mixed
     */
    public function getAnswerAttribute($value)
    {
        return json_decode($value, true);
    }

    /**
     * 设置答案选项修改器
     *
     * @param $value
     */
    public function setAnswerAttribute($value)
    {
        $this->attributes['answer'] = json_encode($value);
    }

    /**
     * 获取创建时间 没有就默认当前时间
     *
     * @param $value
     * @return string
     */
    public function getCreatedAtAttribute($value)
    {
        return Carbon::parse($value)->toDateTimeString();
    }
}
